package com.itheima.utils;


import com.itheima.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class ExcelExportEngine {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static Workbook woriteToExcel(Object object,Workbook workbook,String photoPath) throws Exception {
        // 先把Bean转化为map
        Map<String, Object> map = EntityUtils.entityToMap(object);
        // 循环遍历每一对数据，把日期型的转化为字符串，方便导出
        for (String key : map.keySet()) {
            Object value = map.get(key);
            if(value instanceof Date) {
                map.put(key,sdf.format(value));
            }
        }
        // 获取第一个sheet，整体的思路是循环100个行的100个单元格
        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i < 100; i++) {
            Row row = sheet.getRow(i);  // 获取到空行为止
            if(row == null) {
                break;
            }else {
                for (int j = 0; j < 100; j++) {
                    Cell cell = row.getCell(j);
                    if(cell != null) {
                        writeCell(cell,map); // 获取空单元格不处理，开始写数据
                    }
                }
            }
        }
        if(StringUtils.isNotBlank(photoPath)) {
            File rootPath = new File(ResourceUtils.getURL("classpath:").getPath()); //SpringBoot项目获取根目录的方式
            // 图片  创建一个字节输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 读取图片 放入一个带有缓冲区的图片类中
            BufferedImage bufferedImage = ImageIO.read(new File(rootPath+photoPath));
            String extName = photoPath.substring(photoPath.lastIndexOf(".") + 1).toUpperCase();
            // 把图片写入到了字节输出流中
            ImageIO.write(bufferedImage,extName,byteArrayOutputStream);
            // Patriarch控制图片的写入 和ClientAnchor指定图片的位置
            Drawing patriarch = sheet.createDrawingPatriarch();

            Sheet sheet2 = workbook.getSheetAt(1);
            Row row = sheet2.getRow(0);
            int col1 = ((Double)(row.getCell(0).getNumericCellValue())).intValue();
            int row1 = ((Double) row.getCell(1).getNumericCellValue()).intValue();
            int col2 = ((Double) row.getCell(2).getNumericCellValue()).intValue();
            int row2 = ((Double) row.getCell(3).getNumericCellValue()).intValue();
            // 制定图片的位置  开始列3  开始行2  结束列 4 结束行5
            // 偏移的单位 是一个英式公式的单位  一厘米=360000
            ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,  col1, row1, col2, row2);

            int format = 0;
            switch (extName){
                case "JPG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                case "JPEG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                case "PNG":
                    format = XSSFWorkbook.PICTURE_TYPE_PNG;
            }

            // 开始把图片写入到sheet制定的位置
            patriarch.createPicture(anchor,workbook.addPicture(byteArrayOutputStream.toByteArray(),format));

            workbook.removeSheetAt(1);
        }
        return workbook;
    }

    private static void writeCell(Cell cell, Map<String, Object> map) {
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case FORMULA:
                break;  // 如果是公式直接放行
            default:
                String cellValue = cell.getStringCellValue();
                // 判断获取单元格中的值是否和map中的key保持一致
                if(StringUtils.isNotBlank(cellValue)) {
                    for (String key : map.keySet()) {
                        if(key.equals(cellValue)) {
                            cell.setCellValue(map.get(key).toString());
                        }
                    }
                }
        }
    }
}
